<template>
		<page-meta :root-font-size="fontSizeStore.currentFontSizeRpx"></page-meta>
	<HeadNav :navTitle="pageTitle" />
	<view class="online-supermarket">
		<view class="supermarket-layout">

			<!-- 左侧菜单 -->
			<scroll-view class="category-menu" scroll-y :scroll-into-view="leftScrollInto" scroll-with-animation>
				<view v-for="(category, index) in categories" :key="index" :id="`left-item-${index}`"
					class="category-menu__item" :class="{ 'category-menu__item--active': activeIndex === index }"
					@click="handleCategoryMenuClick(index)">
					<text class="cat_name">{{ category.name }}</text>
				</view>
			</scroll-view>

			<!-- 右侧内容 -->
			<view class="content-panel" @touchmove.stop>
				<!-- button 按钮式单选 -->
				<view class="content-search">
					<view class="content-search__wrap">
						<input class="content-search__input" placeholder="搜索菜品" v-model="searchKeyword"
							placeholder-style="color: #ccc; font-size: 13px;" />
						<view class="content-search__btn content-search__btn--round" @click="handleSearch">
							搜索
						</view>
					</view>
				</view>

				<!-- 筛选区域 -->
				<view class="filter-tabs-container">
					<view class="filter-tabs-header">
						<view class="filter-tab-item" :class="{ 'active': activeFilterTab === 'price' }"
							@click="handleTabClick('price')">
							<text class="text12">价格</text><wd-icon name="arrow-down" size="30rpx"></wd-icon>
						</view>
						<view class="filter-tab-item" :class="{ 'active': activeFilterTab === 'sales' }"
							@click="handleTabClick('sales')">
							<text class="text12">销量</text> <wd-icon name="arrow-down" size="30rpx"></wd-icon>
						</view>
						<!-- <view class="filter-tab-item" :class="{ 'active': activeFilterTab === 'featured' }"
							@click="handleTabClick('featured')">
							<text>特色</text> <wd-icon name="arrow-down" size="30rpx"></wd-icon>
							<view class="tab-count" v-if="featuredFilter.length > 0">
								{{ featuredFilter.length }}
							</view>
						</view> -->
					</view>

					<view class="filter-result-tip" v-if="hasActiveFilter">
						<text>已筛选：</text>
						<text v-if="priceFilter !== 'all'" class="filter-tag">{{ priceFilterText }}</text>
						<text v-if="salesFilter !== 'default'" class="filter-tag">{{ salesFilterText }}</text>
						<text v-for="(item, idx) in featuredFilter" :key="idx" class="filter-tag">{{ featureMap[item]
							}}</text>
						<view class="clear-filter" @click="clearAllFilters">清除全部</view>
					</view>
				</view>

				<!-- 筛选弹窗 -->
				<wd-popup v-model="isFilterPopupOpen" position="bottom" :title="getPopupTitle"
					@close="handlePopupClose">
					<view class="popup-content">
						<view v-if="activeFilterTab === 'price'" class="popup-filter-content">
							<view class="filter-options">
							<view class="filter-option" :class="{ 'active': priceFilter === 'all' }"
									@click="handlePriceFilter('all')">
									价格从高到低
								</view>
								<view class="filter-option" :class="{ 'active': priceFilter === '20-50' }"
									@click="handlePriceFilter('20-50')">
										价格从低到高
								</view>
								
							</view>
						</view>

						<view v-else-if="activeFilterTab === 'sales'" class="popup-filter-content">
							<view class="filter-options">
							<view class="filter-option" :class="{ 'active': salesFilter === 'default' }"
									@click="handleSalesFilter('default')">
									销量从高到低
								</view>
								<view class="filter-option" :class="{ 'active': salesFilter === 'low' }"
									@click="handleSalesFilter('low')">
									销量从低到高
								</view>
							</view>
						</view>

						<!-- <view v-else-if="activeFilterTab === 'featured'" class="popup-filter-content">
							<view class="filter-options">
								<view class="filter-option" :class="{ 'active': featuredFilter.includes('recommend') }"
									@click="toggleFilter('recommend')">
									推荐
								</view>
								<view class="filter-option" :class="{ 'active': featuredFilter.includes('new') }"
									@click="toggleFilter('new')">
									新品
								</view>
								<view class="filter-option" :class="{ 'active': featuredFilter.includes('discount') }"
									@click="toggleFilter('discount')">
									优惠
								</view>
							</view>
						</view> -->

						<!-- <view class="popup-actions">
							<view class="action-btn cancel-btn" @click="handlePopupClose">
								取消
							</view>
							<view class="action-btn confirm-btn" @click="handleFilterConfirm">
								确认
							</view>
						</view> -->
					</view>
				</wd-popup>

				<!-- 商品列表（修复滚动事件触发问题） -->
				<scroll-view ref="rightScrollRef" id="rightScrollView" class="content-goods__scroll" scroll-y="true"
					:scroll-into-view="targetId" scroll-with-animation @scroll="handleRightScroll">
					<view class="content-goods__container">
						<!-- 关键：确保分类标题ID与计算位置的选择器完全匹配 -->
						<view class="category-card" v-for="(category, index) in filteredCategories" :key="index"
							:id="`right-category-${index}`">
							<view class="category-card__title text12" :id="`category-title-${index}`">
								{{ category.name }}
								<span class="category-count text12">({{ category.filteredFoods.length }})</span>
							</view>

							<view v-if="category.filteredFoods.length === 0" class="no-results">
								没有找到符合条件的商品
							</view>

							<view v-for="food in category.filteredFoods" :key="food.id" class="goods-item">
								<view class="goods-item__img">
									<image :src="food.imageUrl || '/src/static/default-goods.png'" :alt="food.name">
									</image>
									<!-- <view v-if="food.isNew" class="tag new-tag">新品</view>
									<view v-if="food.isDiscount" class="tag discount-tag">优惠</view> -->
								</view>
								<view class="goods-item__info">
									<view>
										<text class="goods-item__name text11">{{ food.name }}</text>
										<view v-if="food.isRecommend" class="recommend-badge">推荐</view>
									</view>
									<view class="goods-item__sales text11">销量: {{ food.sales }}份</view>
									<view>
										<text class="goods-item__price text11">￥{{ food.price }}</text>
									</view>
								</view>

								<view class="goods-item__count">
									<view v-if="food.count > 0" class="count-btn count-btn--minus text11"
										@click="handleGoodsCountChange(food, -1)">-</view>
									<text v-if="food.count > 0" class="count-btn__num text11">{{ food.count }}</text>
									<view class="count-btn count-btn--plus text11" @click="handleGoodsCountChange(food, 1)">+
									</view>
								</view>
							</view>
						</view>
						<view class="content-goods__spacer"></view>
					</view>
				</scroll-view>
			</view>
		</view>

		<!-- 底部导航 -->
		<view class="bottom-nav" v-if="!showBottomModel && !isFilterPopupOpen">
			<view class="bottom-nav__cart">
				<view class="cart__wrap">
					<wd-icon name="cart" size="22px"></wd-icon>
					<view v-if="cartCount > 0" class="cart__badge" :class="{ 'cart__badge--dot': cartCount === 0 }">
						{{ cartCount > 99 ? '99+' : cartCount }}
					</view>
				</view>
				<view class="cart__text">购物车</view>
			</view>
			<view class="bottom-nav__price">
				<view class="price__content">
					<text class="price__symbol">¥</text>
					<text class="price__amount">{{ totalAmount }}</text>
				</view>
				<view class="price__desc">配送费</view>
			</view>
			<view class="bottom-nav__reserve">
				<wd-button @click="handleShowPaymentPopup" type="error" size="medium" class="reserve__btn"
					:disabled="cartCount === 0">
					立即预约
				</wd-button>
			</view>
		</view>

		<!-- 支付弹窗 -->
		<view class="payment-popup">
			<wd-action-sheet title="支付" v-model="showBottomModel" @close="handleHidePaymentPopup">
				<view>
					<view class="form-group">
						<view class="form-group__label">地址</view>
						<wd-cell is-link @click="handleShowAddressPanel" value="请选择地址">
						</wd-cell>
					</view>
					<view class="form-group">
						<view class="form-group__label">预约时间</view>
						<wd-datetime-picker v-model="dateTimeValue" :formatter="formatDatetime" />
					</view>
					<view class="payment-section__title">支付方式</view>
					<radio-group @change="onPayTypeChange">
						<label class="payment-method-item" v-for="method in payMethods" :key="method.value">
							<!-- 自定义图标（可替换为 wd-icon） -->
							<view class="payment-method-icon">
								<text :class="`iconfont ${method.icon}`"></text>
							</view>

							<!-- 文字信息 -->
							<view class="payment-method-info">
								<text class="payment-method-name">{{ method.name }}</text>
								<text class="payment-method-desc">{{ method.desc }}</text>
							</view>

							<!-- 单选框 -->
							<radio :value="method.value" :checked="payType === method.value" class="payment-radio" />
						</label>
					</radio-group>
					<view class="payment-section__title">订单备注</view>
					<view class="remark__wrap">
						<wd-textarea border placeholder="请填写评价" />
					</view>


					<view class="payment__footer">
						<view class="payment__footer__btn-wrap">
							<!-- 支付信息 -->
							<view class="payment__info">
								<text>总计</text>
								<text>¥</text>
								<text>{{ totalAmount }}</text>
							</view>

							<!-- 支付按钮 -->
							<view class="payment__footer__footer-btn">
								<wd-button type="error" @click="handleNavigatePayDetail">
									立即支付
								</wd-button>
							</view>
						</view>
					</view>

				</view>
			</wd-action-sheet>
		</view>
	</view>
</template>

<script setup>
	
	import HeadNav from '@/components/HeadNav/index.vue'

import {
	useFontSizeStore
} from '@/stores/fontSizeStore';

const fontSizeStore = useFontSizeStore();
import {
	jifen_chaoshiApi,
	yaodian_chaoshiApi,
	yiyuan_yuyueApi,
	bangding_shebeiApi,
	yiri_cansanApi,
	shenghuo_leiApi,
} from "@/api/products"
import { onLoad } from '@dcloudio/uni-app';

import {
	ref,
	onMounted,
	nextTick,
	computed,
	watch,
	getCurrentInstance as vueGetCurrentInstance
} from 'vue'

// 当前激活的Tab
const activeTab = ref(1)
const paramName = ref("")
const pageTitle=ref("")

const showBottomModel = ref(false);

// 时间选择器相关
const dateTimeValue = ref(Date.now())
const formatDatetime = (type, value) => {
	switch (type) {
		case 'year':
			return value + '年'
		case 'month':
			return value + '月'
		case 'date':
			return value + '日'
		case 'hour':
			return value + '时'
		case 'minute':
			return value + '分'
		default:
			return value
	}
}

// 滚动相关（核心修复：确保变量初始化正确）
const rightScrollRef = ref(null)
const contentPositions = ref([]) // 存储分类标题位置，滚动联动依赖此数据
const activeIndex = ref(0)
const leftScrollInto = ref('')
const targetId = ref('')

// 筛选核心状态
const activeFilterTab = ref('')
const isFilterPopupOpen = ref(false)
const priceFilter = ref('all')
const salesFilter = ref('default')
const featuredFilter = ref([])

// 筛选文本映射
const priceFilterText = computed(() => {
	const map = {
		'all': '全部价格',
		'0-20': '¥0-¥20',
		'20-50': '¥20-¥50',
		'50+': '¥50以上'
	}
	return map[priceFilter.value]
})

const salesFilterText = computed(() => {
	const map = {
		'default': '默认排序',
		'high': '销量从高到低',
		'low': '销量从低到高'
	}
	return map[salesFilter.value]
})

const featureMap = ref({
	'recommend': '推荐',
	'new': '新品',
	'discount': '优惠'
})

const getPopupTitle = computed(() => {
	const map = {
		'price': '价格筛选',
		'sales': '销量筛选',
		// 'featured': '特色筛选'
	}
	return map[activeFilterTab.value] || '筛选'
})

const hasActiveFilter = computed(() => {
	return priceFilter.value !== 'all' || salesFilter.value !== 'default' || featuredFilter.value.length > 0
})

// 商品数据
const categories = ref([])

// 计算筛选后的分类和商品
const filteredCategories = computed(() => {
	return categories.value.map(category => {
		let filteredFoods = [...category.foods].filter(food => {
			if (searchKeyword.value && !food.name.includes(searchKeyword.value)) return false
			if (priceFilter.value === '0-20' && (food.price < 0 || food.price > 20))
				return false
			if (priceFilter.value === '20-50' && (food.price < 20 || food.price > 50))
				return false
			if (priceFilter.value === '50+' && food.price < 50) return false
			if (featuredFilter.value.includes('recommend') && !food.isRecommend) return false
			if (featuredFilter.value.includes('new') && !food.isNew) return false
			if (featuredFilter.value.includes('discount') && !food.isDiscount) return false
			return true
		})
		if (salesFilter.value === 'high') filteredFoods.sort((a, b) => b.sales - a.sales)
		if (salesFilter.value === 'low') filteredFoods.sort((a, b) => a.sales - b.sales)
		return {
			...category,
			filteredFoods
		}
	}).filter(category => category.filteredFoods.length > 0)
})

// 购物车相关
const cartCount = ref(0)
const totalAmount = ref(0.00)
const searchKeyword = ref('')

// 筛选弹窗逻辑
const handleTabClick = (tabType) => {
	activeFilterTab.value = tabType
	isFilterPopupOpen.value = true
}

const handlePopupClose = () => {
	isFilterPopupOpen.value = false
	activeFilterTab.value = ''
}

const handleFilterConfirm = () => {
	handlePopupClose()
	scrollToTop()
}

const handlePriceFilter = (key) => {
	priceFilter.value = key
}

const handleSalesFilter = (key) => {
	salesFilter.value = key
}

const toggleFilter = (filterType) => {
	const index = featuredFilter.value.indexOf(filterType)
	if (index > -1) {
		featuredFilter.value = featuredFilter.value.filter(item => item !== filterType)
	} else {
		featuredFilter.value = [...featuredFilter.value, filterType]
	}
}

const clearAllFilters = () => {
	priceFilter.value = 'all'
	salesFilter.value = 'default'
	featuredFilter.value = []
	scrollToTop()
}

// ===================== 核心修复：滚动相关逻辑 =====================
// 1. 修复 getCurrentInstance 适配（确保选择器能找到元素）
const getCurrentInstance = () => {
	const instance = vueGetCurrentInstance()
	// 兼容 uni-app 不同环境，确保传递正确的组件实例
	return instance ? instance.proxy : window
}

// 2. 修复 scrollToTop（确保滚动到顶部功能正常）
const scrollToTop = async () => {
	await nextTick()
	const query = uni.createSelectorQuery().in(getCurrentInstance())
	query.select('#rightScrollView')
		.fields({
			node: true,
			size: true
		})
		.exec((res) => {
			if (res[0] && res[0].node) {
				res[0].node.scrollTo({
					top: 0,
					animated: true
				})
			}
		})
}

const calculateCategoryPositions = async () => {
	await nextTick()
	const list = filteredCategories.value
	if (list.length === 0) return

	// 清空旧数据
	contentPositions.value = new Array(list.length).fill(null)

	// 获取滚动容器位置（#rightScrollView）
	const scrollQuery = uni.createSelectorQuery()
	scrollQuery.select('#rightScrollView').boundingClientRect()
	scrollQuery.exec(async (res) => {
		const scrollViewRect = res[0]
		if (!scrollViewRect) return

		// 遍历每个分类，获取其标题位置
		for (let index = 0; index < list.length; index++) {
			const query = uni.createSelectorQuery()
			query.select(`#category-title-${index}`).boundingClientRect()
			query.exec((rectRes) => {
				const rect = rectRes[0]
				if (rect) {
					contentPositions.value[index] = {
						top: rect.top - scrollViewRect.top,
						bottom: rect.bottom - scrollViewRect.top,
						height: rect.height
					}
				} else {
					// 如果获取失败，延迟重试
					setTimeout(() => {
						const retryQuery = uni.createSelectorQuery()
						retryQuery.select(`#category-title-${index}`)
							.boundingClientRect()
						retryQuery.exec(retryRes => {
							const r = retryRes[0]
							if (r) {
								contentPositions.value[index] = {
									top: r.top - scrollViewRect.top,
									bottom: r.bottom - scrollViewRect
										.top,
									height: r.height
								}
							}
						})
					}, 50)
				}
			})
		}
	})
}

const handleRightScroll = (e) => {
	const scrollTop = e.detail.scrollTop

	if (contentPositions.value.length === 0) return

	// 滚动到顶部时，激活第一个
	if (scrollTop <= 10) {
		if (activeIndex.value !== 0) {
			activeIndex.value = 0
			leftScrollInto.value = 'left-item-0'
		}
		return
	}

	let matchedIndex = -1
	const len = contentPositions.value.length

	// 从后往前找，找到第一个“顶部在视口内”的分类
	for (let i = len - 1; i >= 0; i--) {
		const pos = contentPositions.value[i]
		if (!pos) continue

		const isLast = i === len - 1
		// 匹配规则：当前滚动距离 >= 分类顶部 - 30px，且 < 分类底部 - 30px（或最后一个分类）
		if (scrollTop >= pos.top - 30 && (isLast || scrollTop < pos.bottom - 30)) {
			matchedIndex = i
			break
		}
	}

	// 更新左侧菜单激活状态
	if (matchedIndex !== -1 && activeIndex.value !== matchedIndex) {
		activeIndex.value = matchedIndex
		leftScrollInto.value = `left-item-${matchedIndex}`
	}
}

// 5. 修复分类点击逻辑（确保右侧滚动到对应分类）
let clickTimer = null

const handleCategoryMenuClick = async (index) => {
	// ✅ 防抖：防止频繁点击
	if (clickTimer) clearTimeout(clickTimer)
	clickTimer = setTimeout(() => {
		clickTimer = null
	}, 300)

	if (index < 0 || index >= filteredCategories.value.length) return

	activeIndex.value = index
	leftScrollInto.value = `left-item-${index}`

	await nextTick()
	targetId.value = ''
	await nextTick()
	targetId.value = `category-title-${index}`

	// 延迟触发高亮
	setTimeout(() => {
		const query = uni.createSelectorQuery()
		query.select('#rightScrollView').boundingClientRect()
		query.exec((res) => {
			const rect = res[0]
			if (rect) {
				handleRightScroll({
					detail: {
						scrollTop: rect.scrollTop
					}
				})
			}
		})
	}, 150)
}

// 6. 强化监听：筛选条件变化时强制重新计算位置
watch([priceFilter, salesFilter, featuredFilter, searchKeyword], () => {
	// 筛选后分类变化，重新获取位置
	setTimeout(() => calculateCategoryPositions(), 100) // 延迟确保DOM更新完成
}, {
	deep: true,
	immediate: true
})

// 7. 页面挂载时初始化位置（确保首次加载有数据）
onLoad(async (options) => {
	console.log("out options:", options)
	const name = options.name;
	paramName.value = name;
	await nextTick()
	activeIndex.value = 0
	leftScrollInto.value = 'left-item-0'
	targetId.value = ''

	await nextTick()
	targetId.value = 'category-title-0'

	const maps = {
		'jifen_chaoshi': 'jifen_chaoshiApi'
	}

	let res = {};
	/*
		jifen_chaoshiApi,
	yaodian_chaoshiApi,
	yiyuan_yuyueApi,
	bangding_shebeiApi,
	yiri_cansanApi,
	shenghuo_leiApi,
	*/
   
	if (name == 'jifen_chaoshi') {
		res = await jifen_chaoshiApi();
		pageTitle.value="积分超市"
	}else if(name == 'yaodian_chaoshi'){
		res = await yaodian_chaoshiApi();
		pageTitle.value="药店超市"
	}else if(name == 'yiyuan_yuyue'){
		res = await yiyuan_yuyueApi();
				pageTitle.value="医院预约"
	}else if(name == 'bangding_shebei'){
		res = await bangding_shebeiApi();
					pageTitle.value="绑定设备"
	}else if(name == 'yiri_cansan'){
		res = await yiri_cansanApi();
			pageTitle.value="一日三餐"
	}else if(name == 'shenghuo_lei'){
		res = await shenghuo_leiApi();
		pageTitle.value="生活类"
	}

	if (res?.code == 200) {
		res.data.forEach((i) => {
			i.foods.forEach((k) => {
				k.count = 0;
			})
		})
		categories.value = res.data;

		// 延迟计算位置
		setTimeout(() => calculateCategoryPositions(), 200)
	}

})
// 其他逻辑保持不变
const handleGoodsCountChange = (food, delta) => {
	if (food.count + delta < 0) return;
	food.count += delta

	let count = 0,
		amount = 0
	categories.value.forEach(cat => {
		cat.foods.forEach(f => {
			count += f.count
			amount += f.count * f.price
		})
	})
	cartCount.value = count
	totalAmount.value = amount
}

const handleSearch = () => {
	scrollToTop()
	uni.hideKeyboard()
}

// const payType = ref('wechat')
// const handlePayTypeChange = (e) => {
//   payType.value = e.detail.value
// }

const payType = ref('wechat')

const payMethods = [{
	value: 'wechat',
	name: '微信支付',
	desc: '推荐使用',
	icon: 'iconfont icon-zhifu-weixinzhifu'
},
{
	value: 'alipay',
	name: '支付宝',
	desc: '安全快捷',
	icon: 'icon-zhifubao'
},
	// { value: 'bank', name: '银行卡', desc: '支持主流银行', icon: 'yinhangqia' }
]

const onPayTypeChange = (e) => {
	payType.value = e.detail.value
}

const handleNavigatePayDetail = () => {
	uni.navigateTo({
		url: '/pages/payment_detail/index'
	})
}

const handleShowPaymentPopup = () => {
	showBottomModel.value = true
}

const handleHidePaymentPopup = () => {
	showBottomModel.value = false
}

const handleShowAddressPanel = () => {
	uni.showToast({
		title: '请选择收货地址',
		icon: 'none'
	})
}
</script>

<style lang="less" scoped>
@import url("@/static/styles/family/onlineSupermarket/index.less");
@import url("@/static/styles/family/onlineSupermarket/tab-select.less");
.cat_name{
	white-space:nowrap; 
	text-overflow:ellipsis;overflow:hidden;
}
</style>